﻿using ZeroSum.Models;

namespace ZeroSum.Extend.Mapper.Extensions;

/// <summary>
///     分部拓展类
/// </summary>
public static class PagedQueryableExtensions
{
    /// <summary>
    ///     分页拓展
    /// </summary>
    /// <typeparam name="TEntity"></typeparam>
    /// <typeparam name="TResponse"></typeparam>
    /// <param name="entities"></param>
    /// <param name="pageNumber">页码，必须大于0</param>
    /// <param name="pageSize"></param>
    /// <returns></returns>
    public static PagedResponseModel<TResponse> ToPagedList<TEntity, TResponse>(this IQueryable<TEntity> entities,
        int pageNumber = 1, int pageSize = 20)
        where TEntity : new() where TResponse : new()
    {
        if (pageNumber <= 0)
            throw new InvalidOperationException($"{nameof(pageNumber)} must be a positive integer greater than 0.");

        var totalCount = entities.Count();
        var items = entities.Skip((pageNumber - 1) * pageSize).Take(pageSize)
            .Select(x => x.MapTo<TResponse>()).ToList();
        var totalPages = (int) Math.Ceiling(totalCount / (double) pageSize);

        return new PagedResponseModel<TResponse>(pageNumber, pageSize, totalCount, items);
    }
}